import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import login from '../views/login/Login'
import adminIndex from '../views/admin/AdminIndex'
import store from '../store'
import admin from '../views/admin/Admin'
import HomeIndex from '../views/home/HomeIndex'
import ArticleDetail from '../views/home/articlePage/ArticleDetail'
import {Message} from 'element-ui'

Vue.use(Router)

let routes = [
  {
    path: '/',
    name: 'HelloWorld',
    component: HelloWorld,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/admin',
    name: 'admin',
    component: admin,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/adminIndex',
    name: 'adminIndex',
    component: adminIndex,
    meta: {
      requiresAuth: true
    }
  },
  {
    path: '/index',
    name: 'index',
    component: HomeIndex,
    meta: {
      requiresAuth: false
    }
  },
  {
    path: '/article',
    name: 'article',
    component: ArticleDetail,
    meta: {
      requiresAuth: false
    }
  }
]

const router = new Router({
  mode: 'history',
  routes
})
// 全局路由守卫,实现前端登录拦截
router.beforeEach(async (to, from, next) => {
  // 守卫需要普通用户登陆的功能
  if (to.meta.requiresAuth) {
    if (store.state.identity) {
      next()
    } else {
      Message.info('请先登录')
      store.commit('setReturnHistory', to.fullPath)
      next({
        path: '/login',
        query: {redirect: to.fullPath}
      })
    }
  } else {
    next()
  }
})

// 保存原来的push函数
let originPush = Router.prototype.push
// 保存原来的replace函数
let originReplace = Router.prototype.replace
// 重写push函数，为解决相同路径跳转报错
// 第一个参数: 告诉原来push方法，你往哪里跳转(传递哪些参数)
// 第二个参数: 成功回调   第三个参数: 失败的回调
Router.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    originPush.call(this, location, resolve, reject)
  } else {
    originPush.call(this, location, () => { }, () => { })
  }
}
// 重写replace函数，为解决相同路径跳转报错
Router.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    originReplace.call(this, location, resolve, reject)
  } else {
    originReplace.call(this, location, () => { }, () => { })
  }
}

export {router}
